import AsyncStorage from '@react-native-async-storage/async-storage';
import { STATISTICS_CONFIG } from '../utils/constants';

class StatisticsService {
  constructor() {
    this.data = {
      totalScrolls: 0,
      totalTime: 0,
      platformStats: {},
      dailyStats: {},
      sessionStats: {
        startTime: null,
        currentScrolls: 0,
        currentTime: 0
      }
    };
    this.isInitialized = false;
  }

  /**
   * 初始化统计服务
   */
  async initialize() {
    try {
      const savedData = await AsyncStorage.getItem(STATISTICS_CONFIG.STORAGE_KEY);
      if (savedData) {
        const parsedData = JSON.parse(savedData);
        this.data = {
          ...this.data,
          ...parsedData,
          sessionStats: {
            startTime: null,
            currentScrolls: 0,
            currentTime: 0
          }
        };
      }
      
      this.isInitialized = true;
      console.log('统计服务初始化完成');
    } catch (error) {
      console.error('初始化统计服务失败:', error);
      this.isInitialized = true; // 即使失败也标记为已初始化
    }
  }

  /**
   * 保存统计数据
   */
  async saveData() {
    try {
      await AsyncStorage.setItem(STATISTICS_CONFIG.STORAGE_KEY, JSON.stringify({
        totalScrolls: this.data.totalScrolls,
        totalTime: this.data.totalTime,
        platformStats: this.data.platformStats,
        dailyStats: this.data.dailyStats,
        lastUpdated: Date.now()
      }));
    } catch (error) {
      console.error('保存统计数据失败:', error);
    }
  }

  /**
   * 开始会话
   */
  startSession() {
    this.data.sessionStats = {
      startTime: Date.now(),
      currentScrolls: 0,
      currentTime: 0
    };
    console.log('统计会话开始');
  }

  /**
   * 结束会话
   */
  async endSession() {
    if (!this.data.sessionStats.startTime) {
      return;
    }

    const sessionDuration = Date.now() - this.data.sessionStats.startTime;
    const sessionScrolls = this.data.sessionStats.currentScrolls;

    // 更新总统计
    this.data.totalTime += sessionDuration;
    this.data.totalScrolls += sessionScrolls;

    // 更新每日统计
    const today = this.getDateKey();
    if (!this.data.dailyStats[today]) {
      this.data.dailyStats[today] = {
        scrolls: 0,
        time: 0,
        sessions: 0
      };
    }
    this.data.dailyStats[today].scrolls += sessionScrolls;
    this.data.dailyStats[today].time += sessionDuration;
    this.data.dailyStats[today].sessions += 1;

    // 重置会话统计
    this.data.sessionStats = {
      startTime: null,
      currentScrolls: 0,
      currentTime: 0
    };

    await this.saveData();
    console.log('统计会话结束:', {
      duration: sessionDuration,
      scrolls: sessionScrolls
    });
  }

  /**
   * 记录滑动
   */
  recordScroll(platform = 'local') {
    if (!this.isInitialized) {
      console.warn('统计服务未初始化');
      return;
    }

    // 更新会话统计
    if (this.data.sessionStats.startTime) {
      this.data.sessionStats.currentScrolls += 1;
      this.data.sessionStats.currentTime = Date.now() - this.data.sessionStats.startTime;
    }

    // 更新平台统计
    if (!this.data.platformStats[platform]) {
      this.data.platformStats[platform] = {
        scrolls: 0,
        time: 0,
        sessions: 0,
        lastUsed: null
      };
    }
    this.data.platformStats[platform].scrolls += 1;
    this.data.platformStats[platform].lastUsed = Date.now();

    // 定期保存（每10次滑动保存一次）
    if (this.data.totalScrolls % 10 === 0) {
      this.saveData();
    }
  }

  /**
   * 记录平台使用时间
   */
  recordPlatformTime(platform, duration) {
    if (!this.data.platformStats[platform]) {
      this.data.platformStats[platform] = {
        scrolls: 0,
        time: 0,
        sessions: 0,
        lastUsed: null
      };
    }
    this.data.platformStats[platform].time += duration;
    this.data.platformStats[platform].lastUsed = Date.now();
  }

  /**
   * 获取总统计
   */
  getTotalStats() {
    return {
      totalScrolls: this.data.totalScrolls,
      totalTime: this.data.totalTime,
      averageScrollsPerMinute: this.data.totalTime > 0 ? 
        Math.round((this.data.totalScrolls / (this.data.totalTime / 60000)) * 100) / 100 : 0
    };
  }

  /**
   * 获取平台统计
   */
  getPlatformStats() {
    const stats = [];
    
    for (const [platform, data] of Object.entries(this.data.platformStats)) {
      stats.push({
        platform,
        scrolls: data.scrolls,
        time: data.time,
        sessions: data.sessions,
        lastUsed: data.lastUsed,
        averageScrollsPerMinute: data.time > 0 ? 
          Math.round((data.scrolls / (data.time / 60000)) * 100) / 100 : 0
      });
    }

    return stats.sort((a, b) => b.scrolls - a.scrolls);
  }

  /**
   * 获取每日统计
   */
  getDailyStats(days = 7) {
    const stats = [];
    const today = new Date();
    
    for (let i = 0; i < days; i++) {
      const date = new Date(today);
      date.setDate(date.getDate() - i);
      const dateKey = this.getDateKey(date);
      
      const dayData = this.data.dailyStats[dateKey] || {
        scrolls: 0,
        time: 0,
        sessions: 0
      };
      
      stats.push({
        date: dateKey,
        scrolls: dayData.scrolls,
        time: dayData.time,
        sessions: dayData.sessions,
        averageScrollsPerMinute: dayData.time > 0 ? 
          Math.round((dayData.scrolls / (dayData.time / 60000)) * 100) / 100 : 0
      });
    }
    
    return stats;
  }

  /**
   * 获取会话统计
   */
  getSessionStats() {
    if (!this.data.sessionStats.startTime) {
      return {
        isActive: false,
        currentScrolls: 0,
        currentTime: 0
      };
    }

    return {
      isActive: true,
      currentScrolls: this.data.sessionStats.currentScrolls,
      currentTime: Date.now() - this.data.sessionStats.startTime
    };
  }

  /**
   * 获取使用趋势
   */
  getUsageTrend(days = 30) {
    const dailyStats = this.getDailyStats(days);
    const totalScrolls = dailyStats.reduce((sum, day) => sum + day.scrolls, 0);
    const totalTime = dailyStats.reduce((sum, day) => sum + day.time, 0);
    
    if (dailyStats.length < 2) {
      return {
        scrollTrend: 0,
        timeTrend: 0,
        trendDirection: 'stable'
      };
    }

    // 计算趋势（最近7天 vs 前7天）
    const recentDays = dailyStats.slice(0, 7);
    const previousDays = dailyStats.slice(7, 14);
    
    const recentScrolls = recentDays.reduce((sum, day) => sum + day.scrolls, 0);
    const previousScrolls = previousDays.reduce((sum, day) => sum + day.scrolls, 0);
    const recentTime = recentDays.reduce((sum, day) => sum + day.time, 0);
    const previousTime = previousDays.reduce((sum, day) => sum + day.time, 0);
    
    const scrollTrend = previousScrolls > 0 ? 
      ((recentScrolls - previousScrolls) / previousScrolls) * 100 : 0;
    const timeTrend = previousTime > 0 ? 
      ((recentTime - previousTime) / previousTime) * 100 : 0;
    
    let trendDirection = 'stable';
    if (scrollTrend > 10) trendDirection = 'increasing';
    else if (scrollTrend < -10) trendDirection = 'decreasing';
    
    return {
      scrollTrend: Math.round(scrollTrend * 100) / 100,
      timeTrend: Math.round(timeTrend * 100) / 100,
      trendDirection,
      totalScrolls,
      totalTime
    };
  }

  /**
   * 获取使用报告
   */
  getUsageReport() {
    const totalStats = this.getTotalStats();
    const platformStats = this.getPlatformStats();
    const dailyStats = this.getDailyStats();
    const sessionStats = this.getSessionStats();
    const usageTrend = this.getUsageTrend();
    
    return {
      summary: totalStats,
      platforms: platformStats,
      daily: dailyStats,
      session: sessionStats,
      trend: usageTrend,
      generatedAt: Date.now()
    };
  }

  /**
   * 导出统计数据
   */
  async exportData() {
    const report = this.getUsageReport();
    const exportData = {
      exportDate: new Date().toISOString(),
      version: '1.0',
      data: report
    };
    
    return JSON.stringify(exportData, null, 2);
  }

  /**
   * 重置统计数据
   */
  async resetData() {
    this.data = {
      totalScrolls: 0,
      totalTime: 0,
      platformStats: {},
      dailyStats: {},
      sessionStats: {
        startTime: null,
        currentScrolls: 0,
        currentTime: 0
      }
    };
    
    await this.saveData();
    console.log('统计数据已重置');
  }

  /**
   * 清理过期数据
   */
  async cleanupOldData(daysToKeep = 90) {
    const cutoffDate = new Date();
    cutoffDate.setDate(cutoffDate.getDate() - daysToKeep);
    const cutoffKey = this.getDateKey(cutoffDate);
    
    let cleaned = 0;
    
    for (const dateKey of Object.keys(this.data.dailyStats)) {
      if (dateKey < cutoffKey) {
        delete this.data.dailyStats[dateKey];
        cleaned++;
      }
    }
    
    if (cleaned > 0) {
      await this.saveData();
      console.log(`清理了 ${cleaned} 条过期统计数据`);
    }
    
    return cleaned;
  }

  /**
   * 获取日期键
   */
  getDateKey(date = new Date()) {
    return date.toISOString().split('T')[0];
  }

  /**
   * 格式化时间
   */
  formatTime(milliseconds) {
    const seconds = Math.floor(milliseconds / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);
    
    if (days > 0) {
      return `${days}天${hours % 24}小时${minutes % 60}分钟`;
    } else if (hours > 0) {
      return `${hours}小时${minutes % 60}分钟`;
    } else if (minutes > 0) {
      return `${minutes}分钟${seconds % 60}秒`;
    } else {
      return `${seconds}秒`;
    }
  }
}

// 创建单例实例
const statisticsService = new StatisticsService();

export default statisticsService;